package cn.com.dbappsecurity.utils;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;

import cn.com.dbappsecurity.frame.exception.FrameException;

public class LocaleUtil {

	private static final Logger LOG = Logger.getLogger(LocaleUtil.class);
	/**
	 * 资源文件路径
	 */
	private static final String RES_LANGUAGE = "/locale/language";
	/**
	 * 默认语言
	 */
	private static final String DEFAULT_LANGUAGE = "zh_CN";
	/**
	 * 缓存语言内容
	 */
	private static Map<String,Properties> languageMap = new HashMap<String,Properties>();
	
	private LocaleUtil(){
	}
	
	/**
	 * 根据异常获取异常描述
	 * @param e
	 * @param language	null则使用默认简体中文
	 * @return
	 */
	public static String getMessage(Throwable throwable,String language){
		String message = null;
		try {
			if(throwable != null){
				if(throwable instanceof FrameException){
					FrameException fe = (FrameException)throwable;
					message = getMessage(String.valueOf(fe.getType()),language);
					Object[] values = fe.getValues();
					if(message != null && values != null){
						for(int i=0;i<values.length;i++){
							message = message.replace("{"+i+"}",values[i].toString());
						}
					}
				}else{
					message = getMessage(throwable.getClass().getSimpleName(),language);
				}
			}
		} catch (Exception e) {
			LOG.error("",e);
		}
		return message;
	}
	
	/**
	 * 根据键获取信息
	 * @param key
	 * @param language
	 * @return
	 * @throws IOException 
	 */
	public static String getMessage(String key,String language) throws IOException{
		if(key != null){
			if(language == null){
				language = DEFAULT_LANGUAGE;
			}
			Properties pro = languageMap.get(language);
			if(pro == null){
				InputStream is = null;
				try {
					is = LocaleUtil.class.getResourceAsStream(RES_LANGUAGE+"_"+language+".properties");
					pro = new Properties();
					pro.load(is);
					languageMap.put(language,pro);
				} finally {
					IOUtils.closeQuietly(is);
				}
			}
			return pro.getProperty(key);
		}else{
			LOG.error("未获取到["+key+"]对应的文本");
		}
		return null;
	}
	
	/**
	 * 根据错误代码获取信息
	 * @param code
	 * @param language
	 * @return
	 * @throws IOException 
	 */
	public static String getMessage(int code,String language) throws IOException{
		return getMessage(String.valueOf(code), language);
	}
}
